<template>
  <div class="app-container">
      <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                      <el-form-item label="设备类型" prop="machineTypeId">
                          <el-input
                                  v-model="queryParams.machineTypeId"
                                  placeholder="请输入设备类型"
                                  @keyup.enter="handleQuery"
                                  style="width: 180px;"
                          />
                      </el-form-item>
                      <el-form-item label="描述" prop="machineTypeDes">
                          <el-input
                                  v-model="queryParams.machineTypeDes"
                                  placeholder="请输入描述"
                                  @keyup.enter="handleQuery"
                                  style="width: 180px;"
                          />
                      </el-form-item>
                      <el-form-item label="制造类型" prop="productionTypeId">
                                  <el-select v-model="queryParams.productionTypeId" placeholder="请选择制造类型" style="width: 150px;">
                                      <el-option
                                              v-for="dict in options"
                                              :key="dict.value"
                                              :label="dict.label"
                                              :value="dict.value"
                                      ></el-option>
                                  </el-select>

                              </el-form-item>
          <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
      </el-form> -->

      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
              <el-button
                      type="primary"
                      plain
                      icon="Plus"
                      @click="handleAdd"
                      v-hasPermi="['SYSConfig:machineType:add']"
              >新增</el-button>
          </el-col>
          <el-col :span="1.5">
              <el-button
                      type="success"
                      plain
                      icon="Edit"
                      :disabled="single"
                      @click="handleUpdate"
                      v-hasPermi="['SYSConfig:machineType:edit']"
              >修改</el-button>
          </el-col>
          <el-col :span="1.5">
              <el-button
                      type="danger"
                      plain
                      icon="Delete"
                      :disabled="multiple"
                      @click="handleDelete"
                      v-hasPermi="['SYSConfig:machineType:remove']"
              >删除</el-button>
          </el-col>
          <el-col :span="1.5">
              <el-button
                      type="warning"
                      plain
                      icon="Download"
                      @click="handleExport"
                      v-hasPermi="['SYSConfig:machineType:export']"
              >导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <t-ag-grid
          :style="{height: height}"
          :column-defs="column"
          :row-data="machineTypeList"
          :row-buffer="20"
          row-selection="multiple"
          :suppress-row-click-selection="true"
          :row-multi-select-with-click="true"
          align="center"
          header-align="center"
          :defaultColDef = "{
              menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
          @selection-changed="selectionChanged"
          />

      <pagination
              v-show="total>0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
      />

      <!-- 添加或修改设备类型对话框 -->
      <el-dialog :title="title" v-model="open" width="590" append-to-body>
          <el-form ref="machineTypeRef" :model="form" :inline="true"  :rules="rules" label-width="100px">
                              <el-form-item label="设备类型" prop="machineTypeId" >
                                <el-input v-model="form.machineTypeId" placeholder="请输入设备类型" style="width: 150px;" />
                              </el-form-item>
                              <el-form-item label="描述" prop="machineTypeDes">
                                  <el-input v-model="form.machineTypeDes" placeholder="请输入描述" style="width: 150px;" />
                              </el-form-item>
                              <el-form-item label="制造类型" prop="productionTypeId">
                                    <el-select v-model="form.productionTypeId" placeholder="请选择制造类型" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in listProductionTypeOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                </el-form-item>
                              <el-form-item label="连续天数" prop="daysParameter">
                                    <el-input-number controls-position="right" v-model="form.daysParameter" placeholder="请输入连续天数" style="width: 150px;"/>
                              </el-form-item>
                              <el-form-item label="ATT下限" prop="attLl">
                                    <el-input-number controls-position="right" v-model="form.attLl" placeholder="请输入ATT下限" style="width: 150px;"/>
                                </el-form-item>
                              <el-form-item label="ATT上限" prop="attUl">
                                    <el-input-number controls-position="right" v-model="form.attUl" placeholder="请输入ATT上限" style="width: 150px;"/>
                                </el-form-item>
                              <el-form-item label="置信区间" prop="ciParameter">
                                    <el-input controls-position="right" v-model="form.ciParameter" placeholder="请输入置信区间" style="width: 150px;"/>
                                </el-form-item>
                              <el-form-item label="取样数Min" prop="sampleSize">
                                    <el-input v-model="form.sampleSize" placeholder="请输入取样数Min" style="width: 150px;"/>
                                </el-form-item>
                              <el-form-item label="TT基准值" prop="referenceTt">
                                    <el-input v-model="form.referenceTt" placeholder="请输入TT基准值" style="width: 150px;"/>
                                </el-form-item>
                              <el-form-item label="CV基准值" prop="referenceCv">
                                    <el-input v-model="form.referenceCv" placeholder="请输入CV基准值" style="width: 150px;"/>
                              </el-form-item>
                              <el-form-item label="OEE重算" prop="oeeRerunFlag">
                                    <el-select v-model="form.oeeRerunFlag" placeholder="请选择OEE重算Flag" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in oeeRerunFlagOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                              </el-form-item>

                              <el-form-item label="OEE良率" prop="yield">
                                    <el-select v-model="form.yield" placeholder="请选择yield" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in oeeYieldOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                              </el-form-item>

                              <el-form-item label="无缺陷MTBI(分)" prop="mtbiStopTar">
                                    <el-input-number controls-position="right" v-model="form.mtbiStopTar" :min="1" :max="1000" placeholder="请输入时间" style="width: 150px;"/>
                              </el-form-item>
                              <el-form-item label="无停止MTBI(分)" prop="mtbiDownTar">
                                    <el-input-number controls-position="right" v-model="form.mtbiDownTar" :min="1" :max="1000" placeholder="请输入时间" style="width: 150px;"/>
                              </el-form-item>
                              <el-form-item label="MTBF(分)" prop="mtbfTar">
                                    <el-input-number controls-position="right" v-model="form.mtbfTar" :min="1" :max="1000" placeholder="请输入时间" style="width: 150px;"/>
                              </el-form-item>
                              <el-form-item label="MTTR(分)" prop="mttrTar">
                                    <el-input-number controls-position="right" v-model="form.mttrTar" :min="1" :max="1000" placeholder="请输入时间" style="width: 150px;"/>
                              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button type="primary" @click="submitForm">确 定</el-button>
                  <el-button @click="cancel">取 消</el-button>
              </div>
          </template>
      </el-dialog>
  </div>
</template>

<script setup name="MachineType">
  import { listMachineType, getMachineType, delMachineType, addMachineType, updateMachineType } from "@/api/SYSConfig/machineType"
  // 获取制造类型 options
  import { listProductionType } from "@/api/SYSConfig/productionType"
  import {  listProductionTypeOptions } from '@/common/options'

  const { proxy } = getCurrentInstance()
  const { oee_b_production_type } = proxy.useDict('oee_b_production_type')

  const machineTypeList = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10000,
      machineTypeId: null,
      machineTypeDes: null,
      productionTypeId: null,
      createUser: null
    },
    rules: {
    }
  })

  const options = ref([])

  const oeeRerunFlagOptions = [
    { label: 'Y', value: 'Y' },
    { label: 'N', value: 'N' }
  ]

  const oeeYieldOptions = [
    { label: '1', value: '1' },
    { label: '-1', value: '-1' }
  ]

  const { queryParams, form, rules } = toRefs(data)

  const height = ref('calc(100% - 66px)')

  const column = [
    { headerName: "制造类型", field: "productionTypeId", headerCheckboxSelection: true, checkboxSelection: true, minWidth: 100, flex: 1 },
    { headerName: "设备类型", field: "machineTypeId",  minWidth: 100, flex: 1 },
    { headerName: "描述", field: "machineTypeDes", minWidth: 300, flex: 1 },
    { headerName: "连续天数", field: "daysParameter", minWidth: 100, flex: 1 },
    { headerName: "置信区间", field: "ciParameter", minWidth: 100, flex: 1 },
    { headerName: "ATT下限", field: "attLl", minWidth: 100, flex: 1 },
    { headerName: "ATT上限", field: "attUl", minWidth: 100, flex: 1 },
    { headerName: "取样数Min", field: "sampleSize", minWidth: 100, flex: 1 },
    { headerName: "TT基准值", field: "referenceTt", minWidth: 100, flex: 1 },
    { headerName: "CV基准值", field: "referenceCv", minWidth: 100, flex: 1 },
    { headerName: "OEE重算", field: "oeeRerunFlag", minWidth: 100, flex: 1 },
    { headerName: "OEE良率", field: "yield", minWidth: 100, flex: 1 },

    { headerName: "无缺陷MTBI(分)", field: "mtbiStopTar", minWidth: 120, flex: 1 },
    { headerName: "无停止MTBI(分)", field: "mtbiDownTar", minWidth: 120, flex: 1 },
    { headerName: "MTBF(分)", field: "mtbfTar", minWidth: 100, flex: 1 },
    { headerName: "MTTR(分)", field: "mttrTar", minWidth: 100, flex: 1 },

    { headerName: "创建人", field: "createUser", minWidth: 100, flex: 1 },
    { headerName: "创建时间", field: "createTime", minWidth: 150, flex: 1 },
    { headerName: "更新人", field: "updateUser", minWidth: 100, flex: 1 },
    { headerName: "更新时间", field: "updateTime", minWidth: 150, flex: 1 }
  ]

  column.forEach((item) => {
    item.filter = 'agMultiColumnFilter'
  })

  const gridApi = ref()

  const selectionChanged  = (params) => {
    gridApi.value = params.api
    const selectedRows = params.api.getSelectedRows()
    single.value = selectedRows.length !== 1
    multiple.value = !selectedRows.length
  }

  // 获取制造类型 options
  const getOptions = () => {
    listProductionType().then((res) => {
      res.rows.forEach((item) => {
        if(options.value.indexOf(item.productionTypeId) === -1){
          options.value.push({
            label: item.productionTypeId,
            value: item.productionTypeId
          })
        }
      })
    })
  }

  /** 查询设备类型列表 */
  function getList() {
    loading.value = true
    listMachineType(queryParams.value).then(response => {
      machineTypeList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      machineTypeId: null,
      machineTypeDes: null,
      productionTypeId: [],
      daysParameter: [],
      ciParameter: [],
      attLl: [],
      attUl: [],
      sampleSize: [],
      referenceTt: [],
      referenceCv: [],
      oeeRerunFlag: [],
      yield: [],
      mtbiStopTar: null,
      mtbiDownTar: null,
      mtbfTar: null,
      mttrTar: null,
      createUser: null,
      createTime: null,
      updateUser: null,
      updateTime: null
    }
    proxy.resetForm("machineTypeRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "添加设备类型"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _machineTypeId = gridApi.value.getSelectedRows()[0].machineTypeId
    getMachineType(_machineTypeId).then(response => {
      form.value = response.data
      open.value = true
      title.value = "修改设备类型"
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["machineTypeRef"].validate(valid => {
      if (valid) {
        if (form.value.machineTypeId != null) {
          updateMachineType(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          addMachineType(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _machineTypeIds = []
    gridApi.value.getSelectedRows().map(item => _machineTypeIds.push(item.machineTypeId) )
    proxy.$modal.confirm('是否确认删除设备类型编号为"' + _machineTypeIds + '"的数据项？').then(function() {
      return delMachineType(_machineTypeIds)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('SYSConfig/machineType/export', {
      ...queryParams.value
    }, `machineType_${new Date().getTime()}.xlsx`)
  }

  getList()
  getOptions()
</script>